<?php 
## include required files
/*******************************/
require_once '../../includefiles.php';
include_once("../../model/users.php");
include_once("../../model/trade.php");
include_once("../../model/leads.php");
include_once("../../model/state.php");
require_once '../../model/city.php';
include_once("../../model/budget.php");
include_once '../../model/paypal.php';
include_once("../../model/usermembership.php");
include_once("../../model/usermembershipdetail.php");
require_once '../../model/membershipplan.php';
require_once '../../model/admindetails.php';
include_once '../../model/email.php';
require_once '../../includes/classes/paypalfunction.php'; // Pay Pal pro Function file 
require_once '../../redirect.php';

checkUserLogin();


if($_SESSION['user_type'] == '3')
{
	@header("location:".SITE_URL."/");
	exit;
}

$userObj = new Model_Users();
$tradeObj = new Model_TRADE();
$leadObj = new Model_Leads();
$objState = new Model_State();
$objCity = new Model_City();
$budgetObj = new Model_Budget();
$paypalObj = new Model_Paypal();
$memberObj	= new Model_Membership();
$memberDetailObj	= new Model_MembershipDetail();
$objPlan = new Model_PLAN();
$adminObj = new Model_AdminDetails();
$emailObj = new Model_Email();


$userId = $_SESSION['getbids_id'];




if($_GET['id1']!='')
{
	$postjobid = base64_decode($_GET['id1']);	
	$jobdetArray = $userObj->getJobDetailsById($postjobid);				
	
	//code for lead price
	$getleadprice =	$leadObj->getLeadPriceByAreaJobTypeBudget($jobdetArray['area'],$jobdetArray['jobtype_id'],$jobdetArray['approx_budget']);
	if($getleadprice['price']=='')
		$getleadprice['price'] = 10;
	$smarty->assign('getleadprice',$getleadprice);
}

if($_POST['btnstep4']=="Submit")
{
	$_SESSION['payment'] = $_POST;
	
	extract($_POST);	
	/*echo "<pre>";
	print_R($_POST);
	die();*/
	$userId = $_SESSION['getbids_id'];
	$postjobid = base64_decode($_POST['jobid']);	
	// job detail	
	$jobdetArray = $userObj->getJobDetailsById($postjobid);
	// trade detail
	$gettradedetail = $tradeObj->getTradeCategoryDetailsById($jobdetArray['trade_id']);	
	
	//jobtype detail
	$getjobtypedetail = $tradeObj->getTradeCategoryDetailsById($jobdetArray['jobtype_id']);

	// homeowner detail
	$homeowneruserDetArray = $userObj->getUserDetailsByUserId($jobdetArray['user_id']);
	
	//tradesman detail 
	$userDetArray = $userObj->getUserDetailsByUserId($userId);
	
	
	$err 	= false ;
	
	/************paypal pro payment**************/
		
		if($finalTotal != 0 && $err == false)
		{ 
			$totalAmount				= $finalTotal;
			$billArray 					= array();
			$billArray['firstname']		= return_post_value($cardfirstname);
			$billArray['lastname']  	= return_post_value($cardllastname);	
			$billArray['address']   	= return_post_value($billingaddr);
			$billArray['city']      	= return_post_value($city);
			$billArray['state']    	 	= return_post_value($state);
			$billArray['country']    	= return_post_value($country);
			$billArray['zipcode']   	= return_post_value($cardpostalcode);
			//$billArray['phone']     	= return_post_value($billphno);
			$billArray['creditcardNo']  = return_post_value($cardnumber);
			$billArray['cvvNo']         = return_post_value($cardcode);
			$billArray['expirydate']    = $carddate."-".$cardmonth."-00";
			$billArray['type']          = return_post_value($cardtype);
			$billArray['userid']   		= 0;
	
			$paymentType 				= urlencode('Sale');				// or 'Sale'
			$firstName 					= urlencode($billArray['firstname']);
			$lastName 					= urlencode($billArray['lastname']);
			$creditCardType 			= urlencode($billArray['type']);
			$creditCardNumber 			= urlencode($billArray['creditcardNo']);
			// Month must be padded with leading zero
			$padDateMonth 				= urlencode(str_pad($cardmonth, 2, '0', STR_PAD_LEFT));				
			$expDateYear 				= $carddate;
			$cvv2Number 				= urlencode($billArray['cvvNo']);
			$address1 					= urlencode($billArray['address']);
			$getcitydetails				= $objCity->getCityDetailsById($billArray['city']);;
			$city = $getcitydetails['city_name'];
			//$phonenum 					= urlencode($billArray['phone']);
			/******* Get Country Name by state Id *******/
			$stateID_code 				= $objState->getStateNameCodeById($billArray['state']);
			$countryIsoCode 			= 'Australia';//$countryObj->getCountryNameCodeById($billArray['country']);
			$state 						= urlencode($stateID_code);
			$zip 						= urlencode($billArray['zipcode']);
			$country 					= urlencode($countryIsoCode);
			$amount 					= urlencode($totalAmount);
			$currencyID 				= urlencode('USD');	
			$InvoiceAndVoucherPrefix 	= "ST";
			
			##----------------------------------------------------
			# Payment Type Select whcih one is default
			##----------------------------------------------------
			
			$getpaypaldetail = $paypalObj->getDetailPaypalAccountById(1);
			$userName					=	$getpaypaldetail['api_key'];//'amoghm_1283422750_biz_api1.gmail.com';//
			$password					=	$getpaypaldetail['password'];//'1283422758';//
			$signature					=	$getpaypaldetail['secrete_key'];//'ATSOTiQAZ.xVkpL0naY0LiADtVy7AOkNU5sxve46LBJ4m8y6qagJApi3';//
			##----------------------------------------------------
			# End Payment Type Select whcih one is default
			##----------------------------------------------------
			
			$nvpStr= "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
				"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
				"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
				// Execute the API operation; see the PPHttpPost function above.
				
			$httpParsedResponseAr 		= PPHttpPost('DoDirectPayment', $nvpStr);
			$nvpStrST 					= explode("&", $nvpStr);
			 
			/******************************************************************************************** 
			// End of Set Paypal Variralbles And Do Direct Transaction
			********************************************************************************************/
			$directPayment 				= true;
	
			if( "SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]) )
			{	
				$paymentLater = true;					
			}
			else
			{
				$err 		= true;
				$err_msg 	= urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]);	
				$_SESSION['error']=	$err_msg;	
			}
		}
		if($err == false)
		{
			if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]) || $finalTotal==0 || $paymentLater == true)
			{
				if($finalTotal > 0)
				{
				
							/************ Add record to membership plan Table ************/
							$membershipArray = array();
							$membershipArray['amount'] = $finalTotal;
							$membershipArray['user_id'] = $userId;
							$membershipArray['dateadded'] = date("Y-m-d H:i:s");
							$orderId = $memberObj->addOrder($membershipArray);
							
							$membershipplanArray 				    = 		array();	
							$membershipplanArray['user_id'] 		= 		$userId;
							$membershipplanArray['mem_id'] 			= 		$orderId;
							$membershipplanArray['plan_id'] 		= 		$_POST['plan_id'];	
							$membershipplanArray['amount'] 	    	= 		$finalTotal;
							$membershipplanArray['add_date']   		= 		date("Y-m-d H:i:s");
							$membershipplanArray['status_date'] 	= 		date("Y-m-d H:i:s");
							$getRandonUpper 						= 		strtoupper(getRandomNumber());
							$invoiceId 								= 		$InvoiceAndVoucherPrefix."I".$getRandonUpper;
							$orderCardArray['invoiceid']			= 		$invoiceId;
							$transactionId 							= 		$httpParsedResponseAr['TRANSACTIONID'];
							$membershipplanArray['transaction_id']  =       $transactionId;	
							$membershipplanArray['transaction_msg'] =       $httpParsedResponseAr["L_LONGMESSAGE0"];	 			
							$membershipplanArray['invoiceid']       =       $invoiceId;	
							$membershipplanArray['status_date']		= 		date("Y-m-d H:i:s");
							$membershipplanArray['status'] 			= 		"paid";
							if($_POST['membershipplan']!='')	
								$membershipplanArray['paymentfor'] 			= 		"membershipplan";
							else	
								$membershipplanArray['paymentfor'] 			= 		"leadprice";
								
							$orderDealId 			    			= 		$memberDetailObj->addRecord($membershipplanArray); // add order
							/*********record added to membership plan***********/
							
						if($_POST['membershipplan']!='')
						{
					
							// code for update user leads
							$getplandetails = $objPlan->getPlanDetailsById($_POST['plan_id']);
							$userArray = array();
							// expiry incremented
							$todaydate = date('Y-m-d');
							$exp_todaydate = explode('-',$todaydate);
							$userArray['expiry_date'] = date('Y-m-d',mktime(0,0,0,$exp_todaydate[1]+$getplandetails['month'],$exp_todaydate[2],$exp_todaydate[0]));
							$userArray['leads']	= $getplandetails['leads']-1;
							$userObj->editUserValueById($userArray,$userId);						
							
						}
					
					
					// code for add user job view table
					$userJobViewArray["userid"] 	= $userId;					
					$userJobViewArray["jobid"] 		= $postjobid;
					$userJobViewArray["message"] 		= $_POST['message'];
					$userJobViewArray["date_added"] = date('Y-m-d');
					$jobviewId = $userObj->addUserViewJOBByValue($userJobViewArray);
					
					
						
						
						
						// send email message to Admin
						$email_message = $emailObj->getEmailById(11);
						$e_subject = $email_message['email_subject'];
						$message = $email_message['email_content']; 
						
						$subject = str_replace('[NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $e_subject);		 
						
						$message = str_replace('[NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $message);
						$message = str_replace('[SITENAME]', SITENAME, $message);
						$message = str_replace('[TRADE]', trim($gettradedetail["trade_category"]), $message);
						$message = str_replace('[JOBTYPE]', trim($getjobtypedetail["trade_category"]), $message); 
						$message = str_replace('[JOBDESC]', trim($jobdetArray["job_desc"]), $message); 
						$message = str_replace('[HOME_NAME]', trim($homeowneruserDetArray["first_name"])." ".trim($homeowneruserDetArray["last_name"]) , $message);
						$message = str_replace('[TRADE_NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $message);
						
						
						$adminEmail = $adminObj->getAdminDetails();
						$to = $adminEmail;
						$from = $adminEmail;
						$fromname= SITENAME;
										 
						$emailTemplate = file_get_contents('../../emailtemplate.html');
						$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
						$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
						$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
						//echo $template_msg; exit;
						if(trim($to) != '')
						@send_mail($to, $template_msg, $subject, $from, $fromname); 
						
						
						// send email message to Tradesman user 
						$email_message = $emailObj->getEmailById(12);
						$e_subject = $email_message['email_subject'];
						$message = $email_message['email_content']; 
						
						$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
								
						
						$message = str_replace('[TRADE]', trim($gettradedetail["trade_category"]), $message);
						$message = str_replace('[JOBTYPE]', trim($getjobtypedetail["trade_category"]), $message); 
						$message = str_replace('[JOBDESC]', trim($jobdetArray["job_desc"]), $message); 
						$message = str_replace('[JOBPOSTCODE]', trim($jobdetArray["area"]), $message); 
						$message = str_replace('[HOME_NAME]', trim($homeowneruserDetArray["first_name"])." ".trim($homeowneruserDetArray["last_name"]) , $message);
						$message = str_replace('[HOME_EMAIL]', trim($homeowneruserDetArray["email"]), $message);
						$message = str_replace('[HOME_MOBNO]', trim($homeowneruserDetArray["phone_number"]), $message);
						$message = str_replace('[SITENAME]', SITENAME, $message);
						
						$to= trim($userDetArray["email"]);
						$adminEmail = $adminObj->getAdminDetails();
						$from = $adminEmail;
						$fromname= SITENAME;
										 
						$emailTemplate = file_get_contents('../../emailtemplate.html');
						$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
						$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
						$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
						//echo $template_msg; exit;
						if(trim($to) != '')
						@send_mail($to, $template_msg, $subject, $from, $fromname); 
				
				}
				if($_POST['membershipplan']!='')
					$_SESSION['msg'] = "<div class='success_msg'><span>Your membership plan has been renewed !</span></div>";
				else	
					$_SESSION['msg'] = "<div class='success_msg'><span>You have paid successfully lead price !</span></div>";
				header('location:'.SITE_URL.'/leads/');
				exit;	
			}
			else
			{	
				$err 		= true;
				$err_msg 	= "";
	
				for($errMsgCnt = 0; $errMsgCnt <= 4; $errMsgCnt++)
				{
					if($httpParsedResponseAr["L_LONGMESSAGE".$errMsgCnt] != "")
					{
						$err_msg .= urldecode($httpParsedResponseAr["L_LONGMESSAGE".$errMsgCnt])."<br />";	
						$_SESSION['error'].=	$err_msg;
					}
				}
			}
		}
}

if($_POST['plan_id']!='')
{
	$getplan_details = $objPlan->getPlanDetailsById($_POST['plan_id']);
	$smarty->assign('getplan_details', $getplan_details);
}

$stateArray	 	= $objState->getAllStateWithActiveStatus();
$smarty->assign('stateArray', $stateArray);

/*$cityArr = $objCity->getAllCityWithActiveStatus();
$smarty->assign("cityArray", $cityArr);
*/
$yr_arr = array();
for($i=date('Y');$i<=date('Y')+15;$i++)
{
	$yr_arr[] = $i;
}
$smarty->assign('yr_arr',$yr_arr);


if($_SESSION['msg'] != ''){
	$smarty->assign("msg", $_SESSION['msg']);	
	unset($_SESSION['msg']);
}
if($_SESSION['sucmsg'] != ''){
	$smarty->assign("sucmsg", $_SESSION['sucmsg']);	
	unset($_SESSION['sucmsg']);
}
if($_SESSION['error'] != ''){
	$smarty->assign("errorMsg", $_SESSION['error']);	
	unset($_SESSION['error']);
}


$active ="leads";
$smarty->assign("active", $active);	



$smarty->display(TEMPLATEDIR.'/modules/leads/payamount.tpl');
unset($smarty);
?>
